/**
 * 
 */
package com.ar.myshares.daos;

import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;

import com.ar.myshares.model.Instrument;

/**
 * @author mac
 *
 */
public class InstrumentDAOImpl implements InstrumentDAO {

	private HibernateTemplate template;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		template = new HibernateTemplate(sessionFactory);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ar.myshares.daos.InstrumentDAO#saveInstrument(com.ar.myshares.model
	 * .Instrument)
	 */
	@Override
	public Instrument saveInstrument(Instrument instrument) {
		Long id = (Long) this.template.save(instrument);
		instrument.setId(id.longValue());
		return instrument;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ar.myshares.daos.InstrumentDAO#removeInstrument(com.ar.myshares.model
	 * .Instrument)
	 */
	@Override
	public void removeInstrument(Instrument instrument) {
		this.template.delete(instrument);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ar.myshares.daos.InstrumentDAO#getInstrument(long)
	 */
	@Override
	public Instrument getInstrument(long id) {
		return template.get(Instrument.class, Long.valueOf(id));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ar.myshares.daos.InstrumentDAO#getAllInstruments()
	 */
	@Override
	public List<Instrument> getAllInstruments() {
		return template.loadAll(Instrument.class);
	}

	@Override
	public Instrument getInstrument(String symbol) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Instrument.class);
		criteria.add(Restrictions.eq("symbol", symbol));
		List<?> results = this.template.findByCriteria(criteria);
		if (results.isEmpty())
			return null;
		return (Instrument) results.get(0);
	}

}
